05 / 05

What is sync.Pool and when should you use it?

sync.Pool is a per-processor cache of reusable objects that reduces GC pressure by allowing frequently allocated short-lived objects to be reused rather than garbage collected.

sync.Pool for buffer reuse
sync.Pool guidelines
  1. 1

    Objects CAN be evicted at any GC cycle — never rely on persistence across requests

  2. 2

    Always Reset/Clear objects before returning them to the pool — stale state causes bugs

  3. 3

    Best for: byte buffers, encoder/decoder instances, temporary structs in hot paths

  4. 4

    The standard library uses Pool internally: fmt package reuses printer objects, json uses encoder pools

  5. 5

    Measure impact with benchmarks: sync.Pool is only beneficial when allocation cost is proven high